package com.hesc.datasync.util;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class ConfigUtil {

    protected final static Logger logger = LoggerFactory.getLogger(ConfigUtil.class);

    private String configPath = getRootPath() + "/syncinf.properties";
    private Properties props;

    @PostConstruct
    public void init() {
        loadConfig();
    }

    public String getProperty(String key) {
        return props.getProperty(key);
    }

    public Set<Object> keys() {
        return props.keySet();
    }

    private void loadConfig() {
        File file = new File(configPath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        InputStream is = null;
        try {
//            is = ConfigUtil.class.getResourceAsStream(configPath);
            is = new FileInputStream(configPath);
            Properties configProps = new Properties();
            configProps.load(is);
            props = configProps;
        } catch (Exception e) {
            logger.error("Failed to load " + configPath, e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public void setProperty(String key, String value) {
        props.setProperty(key, value);
    }

    /**
     * 保存到文件(同步操作)
     */
    public synchronized void save() {

        FileWriter fw = null;
        try {
//            File config = new File(ConfigUtil.class.getResource(configPath).toURI());
            File config = new File(configPath);
            fw = new FileWriter(config);
            props.store(fw, "");
        } catch (Exception e) {
            logger.error("Failed to save " + configPath, e);
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 如果已打成jar包，则返回jar包所在目录
     * 如果未打成jar，则返回target所在目录
     *
     * @return
     */
    public static String getRootPath() {
        // 项目的编译文件的根目录
        String path = null;
        try {
            path = URLDecoder.decode(ConfigUtil.class.getResource("/").getPath(), String.valueOf(StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (path.startsWith("file:")) {
            int i = path.indexOf(".jar!");
            System.out.println(path);
            path = path.substring(0, i);
            System.out.println(path);
//			path = path.substring(0, path.lastIndexOf("/"));
//			System.out.println(path);
            path = path.replaceFirst("file:", "");
            System.out.println(path);
        }
        System.out.println(path);
        // 项目所在的目录
        return new File(path).getParentFile().getAbsolutePath();
    }
}
